# gozerbot/aliases.py
#
#

""" 
    command aliases. this module contains the aliases of commands. aliases
    are stored in the gozerdata/aliases.new json file. 

"""

__copyright__ = 'this file is in the public domain'

### IMPORT SECTION

# gozerbot imports
from gozerbot.persist.persist import Persist
from gozerbot.datadir import datadir
from gozerbot.utils.locking import lockdec
# basic import
import os, thread

### END IMPORT

## LOCK SECTION

aliaslock = thread.allocate_lock()
aliaslocked = lockdec(aliaslock)

#@aliaslocked
def aliasreverse(what):

    """ get the reverse of an alias. 

        :param what: alias to get command for
        :type what: string

        .. literalinclude:: ../../gozerbot/aliases.py
            :pyobject: aliasreverse
    """

    for i, j in aliases.data.iteritems():
        if what == j:
            return i

#@aliaslocked
def aliascheck(ievent):

    """ check if alias is available.

        :param ievent: event to check for aliases

        .. literalinclude:: ../../gozerbot/aliases.py
            :pyobject: aliascheck
    """

    try:

        cmnd = ievent.txt.split()[0]
        alias = aliases.data[cmnd]
        ievent.txt = ievent.txt.replace(cmnd, alias, 1)
        ievent.alias = alias
        ievent.aliased = cmnd

    except (IndexError, KeyError):
        pass

@aliaslocked
def aliassave():

    """ save aliases to json file. 

        .. literalinclude:: ../../gozerbot/aliases.py
            :pyobject: aliassave
    """

    aliases.save()

@aliaslocked
def aliasset(fromm, to):

    """ set an alias. 

        :param from: alias to set
        :type from: string
        :param to: command to alias 
        :type to: string

        .. literalinclude:: ../../gozerbot/aliases.py
            :pyobject: aliasset
    """

    aliases.data[fromm] = to

@aliaslocked
def aliasdel(fromm):

    """ delete an alias.

        :param fromm: alias to delete
        :type fromm: string

        .. literalinclude:: ../../gozerbot/aliases.py
            :pyobject: aliasdel
    """

    try:

        del aliases.data[fromm]
        return 1

    except KeyError:
        pass

def aliasget(fromm):

    """ retrieve an alias. 

        :param fromm: alias to get command for
        :type fromm: string

        .. literalinclude:: ../../gozerbot/aliases.py
            :pyobject: aliasget
    """

    if aliases.data.has_key(fromm): 
        return aliases.data[fromm]

### INIT SECTION

# the aliases object
aliases = Persist(datadir + os.sep + 'aliases.new', init=False)
if not aliases.data:
    aliases.data = {}

### END INIT
